package com.study.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;

public class CompareTest {
	public static void main(String[] args) {
		int count = 10000;
		int threadCount = 10000;

		for(int i=0; i<10; i++){
			test(count, threadCount, (t)->{
				 t.increaseBySyn();
			}, "syn");
		}
		System.out.println("-------------------");
		for(int i=0; i<10; i++){
			test(count, threadCount, (t)->{
				 t.increaseByLock();
			}, "lock");
		}

		System.out.println("-------------------");
		for(int i=0; i<10; i++){
			test(count, threadCount, (t)->{
				 t.increaseBySyn();
			}, "syn");
		}
		System.out.println("-------------------");
		for(int i=0; i<10; i++){
			test(count, threadCount, (t)->{
				 t.increaseByLock();
			}, "lock");
		}
	}

	static void test(int count, int threadCount, Consumer<Counter> consumer, String name){
		Counter counter = new Counter(0);

		CountDownLatch startLatch = new CountDownLatch(threadCount);
		CountDownLatch endLatch = new CountDownLatch(threadCount);
		Runnable task = ()->{
			startLatch.countDown();
			for(int i=0; i<count; i++){
				consumer.accept(counter);
			}
			endLatch.countDown();
		};
		for(int i=0; i<threadCount; i++){
			Thread thread = new Thread(task);
			thread.start();
		}

		try {
			startLatch.await();
			long startTime = System.currentTimeMillis();

			endLatch.await();
			long endTime = System.currentTimeMillis();
			System.out.println(name +"  "+(endTime - startTime)  +"  "+ counter.getCount());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}


	}
}
